package cn.sinjet.viewmodel;

/*import com.amap.navi.PoiSearchActivity;
import com.amap.navi.RouteDetailActivity;
import com.amap.navi.RoutePlanActivity;
import com.amap.navi.SimpleHudActivity;
import com.amap.navi.SimpleNaviActivity;*/

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import cn.sinjet.carassist.ErrDectectSystemActivity;
import cn.sinjet.carassist.ErrQueryActivity;
import cn.sinjet.carassist.FastDetectActivity;
import cn.sinjet.carassist.MainActivity;
import cn.sinjet.carassist.SinjetApplication;
import cn.sinjet.carassist.SinjetUIActivity;
import cn.sinjet.model.carassist.AppModel;
import cn.sinjet.model.carsystem.CarModel;
import cn.sinjet.phone.CallLogActivity;
import cn.sinjet.phone.ContactsActivity;

public class ViewModel implements IOnViewEventListener,OnClickListener{
	SinjetApplication app = SinjetApplication.getInstance();
	private static ViewModel instance = null;
	public static final int MSG_SET_VIEW = 1;
	public static final int MSG_SHOW_DOOR_WARN = 2;
	public static final int MSG_HIDE_PG_DIALOG = 3;
	public static final int MSG_JUMP_PAGE = 4;
	public static final int DATA_NONE = 0;
	public static final int DATA_STRING  = 1;
	public static final int DATA_INT = 2;
	public static final int DATA_BOOL = 3;
	public static final int DATA_OBJECT = 4;
	private Context context = null;
	private int curPage = 0;
	private int prevPage = 0;
	private int lastNaviPage = -1;
	IUpdateUI mUpdateUIListener = null;
	IOnViewEventListener onViewEventListener = null;
	private boolean isInCommonActivity = false;
	private ViewPropertyCenter mUIDataStoreCenter;
	/**
	 */
	public  static ViewModel getIns() {
		if (instance == null) {
			instance = new ViewModel();
		}
		return instance;
	}

	public ViewModel() {
		mUIDataStoreCenter = new ViewPropertyCenter();
	}
    
	public ViewPropertyCenter getUIMsgSaveCenter(){
		if(mUIDataStoreCenter == null)
			mUIDataStoreCenter = new ViewPropertyCenter();
		return mUIDataStoreCenter;
	}
	
    public Context getCurContext(){
    	return context;
    }
    
    public void setInCommonActivity(boolean isIn){
    	this.isInCommonActivity = isIn;
    }
    
    public void onActivityResume(Context context,int pageFlag,IUpdateUI listener){
    	this.context = context;
    	setCurPage(pageFlag);
    	this.mUpdateUIListener = listener;
    }
    
    public String getCurActivityName(){
    	if(context != null){
    		String contextString = context.toString();
    		return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
    	}
        return "";
    }
    /*
	 */
     @SuppressLint("HandlerLeak") private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case MSG_SET_VIEW:{
//				Log.i("new","handleMessage "+msg.getData().getInt("id"));
			    Bundle data = msg.getData();
			    if(data != null){
			    	getUIMsgSaveCenter().handleSetViewProp(data);
			    	if (mUpdateUIListener != null){
//						Log.i("new","handleMessage != null ");
						mUpdateUIListener.updateUI(data);
					}else{
						Log.i("new","handleMessage == null ");
					}
			    }
				
			}break;
			case MSG_JUMP_PAGE:
				int pageId =  msg.getData().getInt("PageId",-1);//
				Log.i("new","handle jumpPage Message:"+pageId);
				int requestCode = msg.getData().getInt("RequestCode",-1);
				if(pageId != -1)
					jumpPageInUIThread(pageId,requestCode);
				break;
			case MSG_SHOW_DOOR_WARN:{
                  Bundle data = msg.getData();
                  int leftFront = data.getInt("leftFront", 0); 
                  int rightFront = data.getInt("rightFront", 0);
                  int leftRear = data.getInt("leftRear", 0);
                  int rightRear = data.getInt("rightRear", 0);
                  int trunk = data.getInt("trunk", 0);
                  if(mUpdateUIListener != null){
                	  mUpdateUIListener.showDoorWarn(new int[]{leftFront,rightFront,leftRear,rightRear,trunk});
                  }
//                  AppModel.getInstance().onDoorState(context,leftFront, rightFront, leftRear, rightRear, trunk);
			  }break;
			}
		}
	};
	
	
	private void sendTagMessage(int id) {
		// TODO Auto-generated method stub
		Message message = new Message();
		message.what = MSG_SET_VIEW;
		Bundle bundle = new Bundle();
		bundle.putInt("id", id);
		message.setData(bundle);
		handler.sendMessage(message);
	}

	/*public void setViewProperty(int id, Object value) {
		if(mPropertiesMap.containsKey(id))
			mPropertiesMap.get(id).setData(value);
		else{
			PropBase newProp = newPropById(id);
			newProp.setData(value);
		    mPropertiesMap.put(id,newProp);
		}
		//sendTagMessage(tag,value,DATA_OBJECT);
	}*/

	public void setViewProperty(int id, String value) {
		if(value == null)
			return;
		Message message = handler.obtainMessage();
		message.what = MSG_SET_VIEW;
		Bundle bundle = new Bundle();
		bundle.putInt("id", id);
		bundle.putInt("type", DATA_STRING);
		bundle.putString("string", value);
		message.setData(bundle);
		handler.sendMessage(message);
		
		/*if(mPropertiesMap.containsKey(tag))
			mPropertiesMap.get(tag).setData(value);
		else{
			PropBase newProp = newPropByTag(tag);
			newProp.setData(value);
		    mPropertiesMap.put(tag,newProp);
		}*/
		//sendTagMessage(tag,value,DATA_STRING);
	}

	public void setViewProperty(int id, int value) {
		Message message = handler.obtainMessage();
		message.what = MSG_SET_VIEW;
		Bundle bundle = new Bundle();
		bundle.putInt("id", id);
		bundle.putInt("type", DATA_INT);
		bundle.putInt("int", value);
		message.setData(bundle);
		handler.sendMessage(message);
		/*if(mPropertiesMap.containsKey(tag)){
			Log.i("kk", "have prop aready");
			mPropertiesMap.get(tag).setData(value);
		}   
		else{
			PropBase newProp = newPropByTag(tag);
			newProp.setData(value);
		    mPropertiesMap.put(tag,newProp);
		}*/
		//sendTagMessage(tag,value,DATA_INT);
	}

	public void refreshView(int id){
		sendTagMessage(id);
	}
	
	public void setViewVisible(int id, int visible) {
		Log.i("kv","setViewVisible:"+id+" "+visible);
		Message message = handler.obtainMessage();
		message.what = MSG_SET_VIEW;
		Bundle bundle = new Bundle();
		bundle.putInt("id", id);
//		bundle.putInt("type", DATA_INT);
		bundle.putInt("visible", visible);
		message.setData(bundle);
		handler.sendMessage(message);
	}

	
	public void setViewProperty(int id){
		sendTagMessage(id);
	}
	
	/*public PropBase getViewProperty(int id){
		if(mPropertiesMap.containsKey(id))
		return mPropertiesMap.get(id);
		return null;
	}*/
	

	@Override
	public void onViewEvent(ViewEvent event) {
		// TODO Auto-generated method stub
//		Log.i("kv", "onViewEvent"+event.getTag());
		if(onViewEventListener != null)
			onViewEventListener.onViewEvent(event);
	}

	public void startActivity(Class<?> cls){
    	Intent intent = new Intent();
    	intent.setClass(context, cls);
    	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    	intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//    	intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
    	context.startActivity(intent);
    }

	public void setOnViewEventListener(IOnViewEventListener listener) {
		// TODO Auto-generated method stub
	       this.onViewEventListener = listener;	
	}
	
	
	/*public void showAlertInUIThread(String strContent,int flag){
		Message message = new Message();
		message.what = MSG_SHOW_ALERT;
		Bundle bundle = new Bundle();
		bundle.putString("CONTENT", strContent);
		bundle.putInt("FLAG",flag);
		message.setData(bundle);
		handler.sendMessage(message);
	}*/

	public void showDoorWarnView(int leftFront,int rightFront,int leftRear,int rightRear,int trunk){
		Message message = new Message();
		message.what = MSG_SHOW_DOOR_WARN;
		Bundle bundle = new Bundle();
		bundle.putInt("leftFront",leftFront);
		bundle.putInt("rightFront",rightFront);
		bundle.putInt("leftRear",leftRear);
		bundle.putInt("rightRear",rightRear);
		bundle.putInt("trunk",trunk);
		message.setData(bundle);
		handler.sendMessage(message);
	}
	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
//		Log.i("ui","set curPage:"+curPage);
		if(this.curPage != curPage){
			prevPage = this.curPage;
			AppModel.getInstance().onLeavePage(prevPage);
			AppModel.getInstance().onEnterPage(curPage);
			this.curPage = curPage;
			Log.i("ui","curPage:"+curPage+"  prePage:"+prevPage);
			switch(curPage){
			case PageDefine.PAGE_NAVI_START:
			case PageDefine.PAGE_POI_SEARCH:
			case PageDefine.PAGE_ROUTE_DETAIL:
			case PageDefine.PAGE_ROUTE_PLAN:
			case PageDefine.PAGE_SIMPLE_HUD:
			case PageDefine.PAGE_SIMPLE_NAVI:
				lastNaviPage = curPage;
				break;
			}
		}
	}
	
	public int getLastNaviPage(){
		return lastNaviPage;
	}

	public void resetNaviPage(){
		lastNaviPage = -1;
	}
	public int getPrevPage() {
		return prevPage;
	}

	public void setPrevPage(int prevPage) {
		this.prevPage = prevPage;
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		Log.i("ui", "onClick:"+view.getId());
		onViewEvent(new ViewEvent(view.getId(), ViewEvent.CLICK));    
	}

	/*intput:页面Id
	 * 
	 */
	public void jumpPage(int pageId,int requestcode){
		Message message = new Message();
		message.what = MSG_JUMP_PAGE;
		Bundle bundle = new Bundle();
		bundle.putInt("PageId", pageId);
		bundle.putInt("RequestCode", requestcode);
		message.setData(bundle);
		handler.sendMessage(message);
	}
	
	public void jumpPage(int pageId){
		Message message = new Message();
		message.what = MSG_JUMP_PAGE;
		Bundle bundle = new Bundle();
		bundle.putInt("PageId", pageId);
		bundle.putInt("RequestCode", -1);
		message.setData(bundle);
		handler.sendMessage(message);
	}
	
	
	public int getCurMyPage() {
		return curPage;
	}
	//it must be called in ui thread
	public void jumpPageInUIThread(int pageId,int requestCode) {
		// TODO Auto-generated method stub
		/*if(curPage == pageId){
			Log.i("ui", "curPage == pageId");
			return;
		}*/
		Log.i("ui", "jumpPage:"+pageId);
		    switch(pageId){
		   /* case PageDefine.PAGE_NAVI_SELECT:
		    	startActivity(RoutePlanActivity.class);
		    	break;
		    case PageDefine.PAGE_ROUTE_DETAIL:
		    	startActivity(RouteDetailActivity.class);
		    	break;*/
		    case PageDefine.PAGE_CAR_ERR_DETECT:
		    	startActivity(ErrDectectSystemActivity.class);
		    	break;
			case PageDefine.PAGE_HOME:
				 startActivity(MainActivity.class);
			    break;
			case PageDefine.PAGE_ERR_QUERY:
				 startActivity(ErrQueryActivity.class);
			    break;
			case PageDefine.PAGE_FAST_DETECT:
				startActivity(FastDetectActivity.class);
			    break;
		/*	case PageDefine.PAGE_SIMPLE_HUD:
				startActivity(SimpleHudActivity.class);
			   break;*/
			case PageDefine.PAGE_PHONE_CALL_LOG:
				startActivity(CallLogActivity.class);
				break;
			case PageDefine.PAGE_PHONE_CONTACT:
				startActivity(ContactsActivity.class);
				break;
			/*case PageDefine.PAGE_SIMPLE_NAVI:{
				Bundle bundle = new Bundle();
				bundle.putBoolean(Utils.ISEMULATOR, mIsEmulatorNavi);
				Intent intent = new Intent(context,SimpleNaviActivity.class);
//				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//				intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				intent.putExtras(bundle);
				context.startActivity(intent);
			}break;
			case PageDefine.PAGE_POI_SEARCH:
				startActivity(PoiSearchActivity.class);
				break;*/
			 default://
					if(isInCommonActivity &&  mUpdateUIListener !=null){//it is not in Sinjet ui activity
						mUpdateUIListener.resetContentView(PageDefine.getLayoutByPageId(pageId));
					}else{//it is already in Sinjet page
						startActivity(SinjetUIActivity.class);
					}
			     break;
			}

			setCurPage(pageId);
	}

	public void jumpPageInUIThread(int pageId){
		jumpPageInUIThread(pageId,-1);
	}
			
	public void startPOISearchForNavi() {
		// TODO Auto-generated method stub
		  /* Intent naviIntent = new Intent(app,PoiSearchActivity.class);
		   naviIntent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
		   naviIntent.putExtra("requestCode", Utils.REQUEST_END_POINT);
		   app.startActivity(naviIntent);*/
	}

	public void setUIListener(IUpdateUI updateUIListener) {
		// TODO Auto-generated method stub
		this.mUpdateUIListener = updateUIListener;
	}

	public void jumpToPreviewPage() {
		// TODO Auto-generated method stub
		switch(prevPage){
		case PageDefine.PAGE_ROUTE_PLAN:
		case PageDefine.PAGE_SCREEN_OFF:
			jumpPage(PageDefine.PAGE_HOME);
			return;
//		   break;
		 }
		 jumpPage(prevPage);
	}

	boolean mIsEmulatorNavi = false;
	public void IsEmulatorNavi(boolean isEmulatorNavi) {
		// TODO Auto-generated method stub
		mIsEmulatorNavi = isEmulatorNavi;
	}

	public void setContext(Context context) {
		// TODO Auto-generated method stub
		this.context = context;
	}

	public void onBackKeyUp() {
		// TODO Auto-generated method stub
		int toPage = PageDefine.PAGE_HOME;
			
		switch(curPage){
		case PageDefine.PAGE_SETTING_NAVI:// =	0x0005; //
			finishActivity();
			return;
//			break;
			
		case PageDefine.PAGE_ERR_QUERY:// =	0x0082; //
		case PageDefine.PAGE_CAR_CONDITION:// =	0x0001; //
		case PageDefine.PAGE_CAR_METER:// =	0x0003; //
//		case PageConstant.PAGE_SETTINGS: =	0x0004; 
		case PageDefine.PAGE_SETTING_GENERAL:// = 0x0006;
			break;
		case PageDefine.PAGE_ABOUT:// = 0x0008;
		case PageDefine.PAGE_CONTACT_US:// = 0x0009;
		case PageDefine.PAGE_HUD_SET:
		case PageDefine.PAGE_HUD_SET_SCREEN:
			
			toPage = PageDefine.PAGE_SETTING_GENERAL;
			break;
		case PageDefine.PAGE_NAVI_SIMPLE_SET:// = 0x000A;
			if(prevPage == PageDefine.PAGE_SIMPLE_NAVI)
				toPage = PageDefine.PAGE_SIMPLE_NAVI;
			else toPage = PageDefine.PAGE_SETTING_GENERAL;
			break;
		
		case PageDefine.PAGE_CAR_TPMS:// = 0x0024;
			break;
			
		case PageDefine.PAGE_OBD_DISCRIPTION:// = 0x0020;
		case PageDefine.PAGE_CAR_CONDITION_DETAIL:// = 0x0021;
		case PageDefine.PAGE_CAR_CONDITION_VIN:// = 0x0022;
		case PageDefine.PAGE_CAR_ERR_DETECT:// = 0x0023;
		case PageDefine.PAGE_FAST_DECTECT:// = 0x0025;
			toPage = PageDefine.PAGE_CAR_CONDITION;
		    break;
		}
		jumpPageInUIThread(toPage);
	}
	
	public void showAlertDialog(String positive,String negative, String content, final OnMyDlgActionListener actionListener) {
		if(mUpdateUIListener != null){
			mUpdateUIListener.showAlertDialog(positive,negative, content, actionListener);
		}
	}

	public void showToast(String string) {
		// TODO Auto-generated method stub
		CarModel.getInstance().showToastInUIThread(string);
	}

	public void finishActivity() {
		// TODO Auto-generated method stub
		if(mUpdateUIListener != null)
			mUpdateUIListener.finishActivity();
	}
}
	
	